package com.workflow.sdk.domain.model.entity;

import com.design.ddd.Entity;
import com.workflow.sdk.core.WorkflowExecutorResult;
import com.workflow.sdk.domain.convert.WorkflowExecuteConverter;
import com.workflow.sdk.domain.model.entity.dto.WorkflowExecuteDto;
import com.workflow.sdk.domain.model.entity.dto.WorkflowerExecuteParamDto;
import com.workflow.sdk.domain.model.idenfifer.WfExecutorIdentify;
import com.workflow.sdk.infra.repository.factories.WorkFlowRepositoryFactory;
import com.workflow.sdk.infra.util.WorkflowExecuteStrategyFactory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Optional;


/**
 * Workflow execute do
 *
 * @description: 执行流程领域模型，作为基础域
 * @author: cyj
 * @date 2022 -07-19 14:22:32
 */
@Data
@Slf4j
public class WorkflowExecuteEntity extends Entity<WfExecutorIdentify> {
    /**
     * 当前活跃节点
     */
    private WorkflowExecuteDto activeNode;
    /**
     * 所有执行节点
     */
    private List<WorkflowExecuteDto> workflowExecuteDtos;

    private WorkflowExecuteEntity() {
    }

    /**
     * 创建执行流程
     *
     * @return
     */
    public void createWorkflowExecute() {

        WorkFlowRepositoryFactory.workflowExecuteRepositoryService.saveBatch(WorkflowExecuteConverter.INSTANCE.workflowExecuteDtoToPo(this.workflowExecuteDtos));

    }

    /**
     * 执行
     */
    public <T> WorkflowExecutorResult workflowExecute(WorkflowerExecuteParamDto<T> workflowerExecuteParamDto) {

        log.info("workflowExecute: 执行流程!");
        WorkflowExecutorResult workflowExecutorResult = Optional.ofNullable(
                // 执行具体流程业务
                WorkflowExecuteStrategyFactory.getExecutor(super.identify.getWorkflowCode(),
                        this.activeNode.getNode())
                        .execute(workflowerExecuteParamDto.getParam(),
                                workflowerExecuteParamDto.getRemark())

        ).orElse(new WorkflowExecutorResult());
        log.info("workflowExecute: 执行流程, 返回：{}!", workflowExecutorResult);

        log.info("workflowExecute: 流转流程!");
        // 流转流程
        WorkFlowRepositoryFactory.workflowExecuteRepositoryService.
                changeWorkflowExecute(workflowExecutorResult.getNextNode(),
                        WorkflowExecuteConverter.INSTANCE.workflowExecuteDtoToPo(this.activeNode),
                        WorkflowExecuteConverter.INSTANCE.workflowExecuteDtoToPo(this.workflowExecuteDtos),
                        workflowerExecuteParamDto.getRemark());

        return workflowExecutorResult;
    }
}
